import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpClient {

    DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    public UdpClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }


    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scan = new Scanner(System.in);
        while(true) {
            //要做四个事情
            System.out.print("->");
            //1.从控制台读取要发送请求的数据
            if(!scan.hasNext()) {
                break;
            }
            String request = scan.next();

            //2.构造请求并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length
            , InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //3.读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4060],0,4060);
            socket.receive(responsePacket);
            //4.把响应显示到控制台上
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());

            System.out.println(response);
         }
    }

    public static void main(String[] args) throws IOException {
        UdpClient client = new UdpClient("127.0.0.1",9090);
        client.start();
    }
}
